﻿
using ServerFramework.Net.Tcp;
using ServerFramework.Tools;
using System;
using MsgDefine;

namespace SocketServer
{
    public class GameStart : ServerFramework.Tools.ServerStart
    {
        private static GameStart _instance;
        public static GameStart Instance { get { if (_instance == null) { _instance = new GameStart(); } return _instance; } }
        public static TcpServer server;
        public override void Start(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Log.WriteLog(ELogLevel.LOG_INFO, "version:" + ConfigUtil.AppSetting("version"));
            Log.WriteLog(ELogLevel.LOG_INFO, "name:" + ConfigUtil.AppSetting("name"));
            server = new TcpServer(100);
            server.onClientConn += Server_onClientConn;
            server.onRecvMessage += Server_onRecvMessage;
            server.onClientClose += Server_onClientClose;
            server.Start(8080);
            ///启动log线程
            Console.ResetColor();
            Log.Instance.StartLog(ConfigUtil.AppSetting("name"), "/Log");
            Log.WriteLog(ELogLevel.LOG_INFO, "server start success");
        }

        private void Server_onClientClose(UserToken arg1, string arg2)
        {
            Console.WriteLine("客户端离开");
        }

        private void Server_onRecvMessage(ServerFramework.Net.Msg.MsgPacket obj)
        {
            if ((EMsgID)obj.msgId == EMsgID.MSGID_HELLOW_WORLD)
            {
                ReqHelloworld msg = ServerFramework.Net.Msg.MsgPacket.PacketToObj<ReqHelloworld>(obj);
                Console.WriteLine(msg.ReqString);
                ResHelloworld send = new ResHelloworld();
                send.ResString = "你好我是服务器";
                obj.GetToken<UserToken>().Send(send.Pack());
            }
            else
            {
                Console.WriteLine("未知消息");
            }
        }

        private void Server_onClientConn(UserToken obj)
        {
            Console.WriteLine("客户端进入");
        }

        public override void Stop()
        {
            base.Stop();
            server.Close();
        }
    }
}
